<template>
  <div ref="pie" :id="'pie' + ids" style="height:140px"></div>
</template>
<script>
export default {
  // 父组件传值
  props: {
    /**
     * chartsContent：图表信息
     * 数组类型
     */
    echartsData: {
      type: Array,
      default: () => []
    },
    /**
     * heightData：图表高度
     * 默认为300px
     */
    heightData: {
      type: String,
      default: "200px"
    },
    // ids：dom的id，可用于区分图表
    ids: {
      type: String,
      default: ""
    },
    title: {
      type: String,
      default: ""
    },
    legend: {
      type: Array,
      default: () => []
    },
    pieSize: {
      type: Array,
      default: () => ["45%", "60%"]
    },
    isRing: {
      type: Boolean,
      default: false
    },
    color: {
      type: Array,
      default: ["#c73a77", "#c76f3a", "#8f3ff2", "#3152f7", "#11baf7"]
    },
    allObj: {
      type: Object,
      default: () => ({
        titleShow: false
      })
    },
    legendTop: {
      type: String,
      default: "18%"
    },
    piePosition: {
      type: Array,
      default: () => ["70%", "50%"]
    },
    toolTipCallBack: {}
  },
  mounted() {
    //使用nextTick为了保证dom元素都已经渲染完毕
    this.$nextTick(() => {
      this.init();
    });
  },
  data() {
    return {
      option: {
        title: {
          show: this.allObj.titleShow,
          // text: this.allObj.text,
          // subtext: this.allObj.name,
          // x: this.allObj.x || "55%",
          // y: this.allObj.y || "48%",
          // textStyle: {
          //   color: "#11baf7",
          // },
          // subtextStyle: {
          //   color: "#11baf7",
          //   y: "55%",
          // },
          zlevel: 0,
          text: [
            "{value|" + this.allObj.text + "}",
            "{name|" + this.allObj.name + "}"
          ].join("\n"),
          rich: {},
          top: "center",
          left: "center",
          textStyle: {
            rich: {
              value: {
                color: "#11baf7",
                fontSize: 20,
                fontWeight: "bold",
                lineHeight: 20
              },
              name: {
                color: "#11baf7",
                lineHeight: 20
              }
            }
          }
        },
        legend: {
          orient: "vertical",
          // top: this.legendTop,
          right: "right",
          textStyle: {
            color: "#11baf7"
          },
          formatter: (v, y) => {
            let data = this.allObj.data;
            let total = 0;
            let tarValue;
            for (let i = 0; i < data.length; i++) {
              total += data[i].value;
              if (data[i].name == v) {
                tarValue = data[i].value;
              }
            }
            let p = ((tarValue / total) * 100).toFixed(2) + "%";
            // return v + " " + tarValue + "       " + p;
            if (v == "IP") {
              return v + "                      " + p;
            }
            return v + "                  " + p;
          },
          ...(this.allObj.legendPosition
            ? this.allObj.legendPosition
            : { right: "2%" })
        },
        tooltip: {
          trigger: "item",
          // formatter: "{a} <br/>{b} : {c} ({d}%)",
          formatter: this.toolTipCallBack
            ? this.toolTipCallBack()
            : "{b} : {c} ({d}%)",
          /* 解决tooltip被遮挡 */
          confine: true
        },
        graphic: {
          type: "text",
          // left: "-5%",
          // top: "90%",
          // 这里根据需要可以塞数据
          style: {
            text: ""
            // fill: "red",
          }
        },
        color: this.allObj.color || this.color,
        toolbox: {
          show: true,
          feature: {
            // dataView: {
            //   // show: true,
            //   readOnly: true,
            // },
            // magicType: { type: ["line", "bar"] },
            // restore: {},
            // saveAsImage: {},
          }
        },
        // 图表数据
        series: []
      }
    };
  },
  // 监听
  watch: {
    // 监听chartsContent
    echartsData: {
      handler: function(newVal) {
        // 判断图表信息非空
        this.$nextTick(() => {
          this.init();
        });
      },
      deep: true
    }
  },
  methods: {
    // init：渲染表格
    init() {
      // 选择对应dom
      const idName = "pie" + this.ids;
      const Charts = idName && document.getElementById(idName);
      // 判断图表是否有数据
      if (this.echartsData.length === 0) {
        Charts.innerHTML = "无数据";
        // 加载重绘
        Charts.removeAttribute("_echarts_instance_");
      } else {
        // 初始化echarts实例
        const pieCharts = this.$echarts.init(Charts);
        this.option.title.text = [
          "{value|" + this.allObj.text + "}",
          "{name|" + this.allObj.name + "}"
        ].join("\n");
        this.option.series = [];
        let colorList = ["#2639d9", "#a367e6", "#b1a7f1", "#d4d7f7", "#3bb76c"];
        this.option.series.push({
          type: "pie",
          data: this.echartsData,
          // radius: ['50%','60%'],
          label: {
            show: false,
            fontSize: 12,
            // formatter: "{b}:{d}%",
            // formatter: "{d}%",
            rich: {
              b: {
                fontSize: 12,
                height: 60,
                lineHeight: 20,
                align: "center" // 设置文字居中
              },
              per: {
                color: "#eee",
                backgroundColor: "#334455",
                padding: [2, 4],
                borderRadius: 2,
                align: "center"
              }
            }
          },
          labelLine: {
            show: true
          },
          center: this.piePosition,
          radius: this.isRing ? this.pieSize : "50%",
          ...this.allObj.seriesItem
          // avoidLabelOverlap: true, // 防止标签重叠
          // minAngle: 10 //最小的扇区角度（0 ~ 360），用于防止某个值过小导致扇区太小影响交互
          // }
        });
        // 显示图表
        pieCharts.setOption(this.option, true);
        pieCharts.on("click", params => {
          this.$emit("nodeClick", params);
        });
        // 图表大小自适应
        window.addEventListener("resize", () => {
          pieCharts.resize();
        });
      }
    }
  }
};
</script>
<style>
.line-charts {
  height: 100%;
}
</style>
